<?php
namespace app\admin\controller;

use think\Controller;
use app\common\model\Template as TemplateModel;

class Template extends Controller
{
    /**
     * 获取模板列表
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return json
     */
    public function list()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $keyword = input('keyword/s', '');

        $where = [];
        if ($keyword) {
            $where[] = ['name', 'like', "%{$keyword}%"];
        }

        $list = TemplateModel::where($where)
            ->page($page, $limit)
            ->select();
            
        $count = TemplateModel::where($where)->count();

        return json([
            'code' => 1,
            'data' => [
                'list' => $list,
                'total' => $count,
                'last_page' => ceil($count / $limit)
            ]
        ]);
    }

    /**
     * 添加模板
     * @param string $name 模板名称
     * @param string $content 模板内容
     * @param int $type 模板类型
     * @return json
     */
    public function add()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('Template');
        if (!$validate->scene('add')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        if (TemplateModel::create($data)) {
            return json(['code' => 1, 'msg' => '添加成功']);
        }
        return json(['code' => 0, 'msg' => '添加失败']);
    }

    /**
     * 编辑模板
     * @param int $id 模板ID
     * @param string $name 模板名称
     * @param string $content 模板内容
     * @return json
     */
    public function edit()
    {
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('Template');
        if (!$validate->scene('edit')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $template = TemplateModel::find($data['id']);
        if (!$template) {
            return json(['code' => 0, 'msg' => '模板不存在']);
        }

        if ($template->save($data)) {
            return json(['code' => 1, 'msg' => '编辑成功']);
        }
        return json(['code' => 0, 'msg' => '编辑失败']);
    }

    /**
     * 删除模板
     * @param int $id 模板ID
     * @return json
     */
    public function delete()
    {
        $id = input('id/d', 0);
        if (!$id) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }

        if (TemplateModel::destroy($id)) {
            return json(['code' => 1, 'msg' => '删除成功']);
        }
        return json(['code' => 0, 'msg' => '删除失败']);
    }
} 